package multi_thread.basic;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * @author Cheng Jun
 * Description: Collections.synchronizedXXX 系列方法可以将线程不安全的集合 转化成线程安全的集合
 * @version 1.0
 * @date 2021/10/9 21:11
 */
public class SynchronizedCollectionsExample {

    public static void main(String[] args) throws ExecutionException, InterruptedException {

        // List<Integer> numList = new ArrayList<>();
        // Collections.synchronizedXXX 方法 可以将线程不安全的集合转化成 线程安全的集合，底层使用的 synchronized(mutex)
        List<Integer> numList = Collections.synchronizedList(new ArrayList<>());
        ExecutorService executorService = Executors.newFixedThreadPool(100);
        for (int i = 0; i < 10000; i++) {
            executorService.submit(() -> {
                numList.add(1);
            });
        }
        executorService.shutdown();
        while (true) {
            if (executorService.isTerminated()) {
                System.out.println("不安全的集合" + numList.size());
                break;
            }
        }
    }
}
